package com.company.aicrawlers.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.aicrawlers.entity.CollectTaskPlatform;
import com.company.aicrawlers.mapper.CollectTaskPlatformMapper;
import com.company.aicrawlers.service.CollectTaskPlatformService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 任务-平台配置 Service实现类
 * 
 * @author AI Crawlers
 * @since 2025-10-10
 */
@Slf4j
@Service
public class CollectTaskPlatformServiceImpl extends ServiceImpl<CollectTaskPlatformMapper, CollectTaskPlatform> 
        implements CollectTaskPlatformService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchCreate(Long taskId, List<String> platforms, Integer totalQuestionCount) {
        List<CollectTaskPlatform> list = new ArrayList<>();
        for (int i = 0; i < platforms.size(); i++) {
            CollectTaskPlatform platform = new CollectTaskPlatform();
            platform.setTaskId(taskId);
            platform.setPlatformName(platforms.get(i));
            platform.setPlatformStatus("pending");
            platform.setCompletedQuestionCount(0);
            platform.setTotalQuestionCount(totalQuestionCount);
            platform.setSuccessCount(0);
            platform.setFailCount(0);
            platform.setSortOrder(i + 1);
            platform.setEnabled(true);
            platform.setCreateTime(LocalDateTime.now());
            list.add(platform);
        }
        this.saveBatch(list);
        log.info("批量创建平台配置成功, taskId={}, platforms={}", taskId, platforms);
    }

    @Override
    public List<CollectTaskPlatform> getByTaskId(Long taskId) {
        LambdaQueryWrapper<CollectTaskPlatform> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CollectTaskPlatform::getTaskId, taskId);
        wrapper.orderByAsc(CollectTaskPlatform::getSortOrder);
        return this.list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePlatformStats(Long taskId, String platformName, boolean success) {
        LambdaUpdateWrapper<CollectTaskPlatform> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(CollectTaskPlatform::getTaskId, taskId);
        wrapper.eq(CollectTaskPlatform::getPlatformName, platformName);

        if (success) {
            wrapper.setSql("success_count = success_count + 1");
        } else {
            wrapper.setSql("fail_count = fail_count + 1");
        }

        this.update(wrapper);
        log.debug("更新平台统计, taskId={}, platform={}, success={}", taskId, platformName, success);
    }
}

